<?php

namespace App\Tcp;

use EasySwoole\EasySwoole\ServerManager;
use EasySwoole\EasySwoole\Swoole\EventRegister;
use EasySwoole\Socket\Bean\Caller;

class TcpClient
{

    public static function create()
    {
        $server = ServerManager::getInstance()->getSwooleServer();

        $subPort1 = $server->addlistener('0.0.0.0', 9502, SWOOLE_TCP);
        $subPort1->set(
            [
                'open_length_check' => false, //不验证数据包
            ]
        );

        $subPort1->on('connect', function (\swoole_server $server, int $fd, int $reactor_id) {
            echo "fd:{$fd} 已连接\n";
            if ($fd === 1) User::cleanLoginCash();
            $str = '恭喜你连接成功';
            $server->send($fd, $str);
        });
        $subPort1->on('close', function (\swoole_server $server, int $fd, int $reactor_id) {
            echo "fd:{$fd} 已关闭\n";
        });
        $subPort1->on('receive', function (\swoole_server $server, int $fd, int $reactor_id, string $data) {

            if (($requestData = json_decode($data, true)) && ($type = $requestData['request_type'] ?? '') && ($param = $requestData['param'] ?? [])) {
                switch ($type) {
                    case 1:
                        $result = User::login($param, $fd);
                        $server->send($fd, $result);
                        break;

                    case 2:
                        $result = Message::recieve($param, $fd);
                        break;

                    case 3:
                        $result = User::addGroup($param, $fd);
                        $server->send($fd, $result);
                        break;
                    
                    default:
                        break;
                }
            }
        });
    }

}